const FrBaseService = require('../../../framework/platform/service/base_service.js');
const dbUtil = require('../../../framework/database/db_util.js');
const AdminModel = require('../../../framework/platform/model/admin_model.js');
const UserModel = require('../model/user_model.js');
const appCode = require('../../../framework/core/app_code.js');

class BaseService extends FrBaseService {

    constructor() {
        super();
    }

    async initSetup() {
        let F = (c) => 'pbs_' + c;
        const INSTALL_CL = 'user';
        const COLLECTIONS = ['admin', 'log', 'system_config', 'user'];
        if (await dbUtil.isExistCollection(F(INSTALL_CL))) {
            return;
        }
        let arr = COLLECTIONS;
        for (let k = 0; k < arr.length; k++) {
            if (!await dbUtil.isExistCollection(F(arr[k]))) {
                await dbUtil.createCollection(F(arr[k]));
            }
        }

        if (await dbUtil.isExistCollection(F('admin'))) {
            let adminCnt = await AdminModel.count({});
            if (adminCnt == 0) {
                let data = {};
                data.ADMIN_NAME = 'admin';
                data.ADMIN_PASSWORD = 'e10adc3949ba59abbe56e057f20f883e';
                data.ADMIN_DESC = '超管';
                data.ADMIN_TYPE = 1;
                await AdminModel.insert(data);
            }
        }
    }

    async getUserInfo(openid) {
        const userInfo = await UserModel.getOne({ user_openid: openid });
        if (!userInfo || userInfo.user_openid !== openid) {
            this.AppError('请登陆', appCode.USER_LOGIN);
        }
        return userInfo;
    }

}

module.exports = BaseService;